<template>
    <view class="content ">
        <van-nav-bar :title="scrolling? navBarTitle : '' " left-arrow @click-left="onClickLeft"> </van-nav-bar>
        <scroll-view :refresher-enabled="false" class="scroll-content" scroll-y @scroll="scrollPage" show-scrollbar="false">

            <view class="bgCart">
                <view class="cartTop">
                    <view class="cartAd">
                        <view class="cartAd_title">购物结算</view>
                    </view>
                    <view class="userInfo">
                        <view class="userInfo_left" v-if="ebUserAddressList.length>0 && !loading">
                            <view class="user_address" @click="changeAddress(1)">
                                <!-- <text>{{ houseName }}</text> -->
                                <view class="user_address_text">{{ userAdderssDefault.detail }}</view>
                                <van-icon name="arrow" size="11" style="margin-left:10px ;" />
                            </view>
                            <view class="userInfo_bottom">
                                <text class="userName" style="margin-right: 10px;">{{ userAdderssDefault.realName }}</text>
                                <text class="userTel">{{ userAdderssDefault.phone }}</text>
                            </view>
                        </view>
                        <view class="userInfo_left" v-else>
                            <view class="user_address">
                                <text @click="toastMsg">请先选择地址再进行结算</text>
                                <van-icon name="arrow" size="11" style="margin-left:10px ;" @click="changeAddress(0)" />
                            </view>
                        </view>
                        <view class="userInfo_right deliveryMethod">
                            <view class="tab-bar gray">
                                <view
                                    class="tabbar-item"
                                    v-for="(item, index) in tabBarList"
                                    @click="changeTab(index, $event, item.name)"
                                    :class="{ active: index === currentIndex }"
                                    :key="index">
                                    {{ item.name }}
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <!-- <view class="line" v-if="ebUserAddressList.length>0"></view> -->

                <!-- 选择自提并且 地址不为空 -->
                <template v-if="ebUserAddressList.length > 0 && currentIndex===0">
                    <!-- 有自提点 -->
                    <view class="cart_content self-pickup " v-if="merchantList.length > 0">
                        <view class="self-pickup-left" @click="toSelectPick">
                            <view class="self_pickup_pic"> <img :src="foundEleMerchant.imgUrl ? foundEleMerchant.imgUrl:'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/zitiPic.png'" alt="" mode="widthFix"> </view>
                            <view class="self_pickup_left_l">
                                <view class="left_top"> <text class="self_pickup_name">{{foundEleMerchant.merchantName || '加载中...'}}</text><text class="distance" >距离{{ distance }}</text>
                                </view>
                                <view class="left_bottom">营业时间：{{ foundEleMerchant.businessHours }}</view>
                            </view>
                        </view>
                        <view class="self-pickup-right" v-if="foundEleMerchant"  @click="toMap(foundEleMerchant)">
                            <img
                                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/self_pickup.png"
                                alt=""
                                style="width: 16px; height: 16px;">
                            <view class="spr_text">当前自提点</view>
                        </view>
                    </view>
                    <!-- 无自提点 -->
                    <view class="cart_content self-pickup " v-else>
                        <view class="no-self-pickup"> 当前小区暂无自提点 </view>
                    </view>
                </template>
                <!-- 同城配送 -->
                <template v-if="currentIndex===1">
                  <view class="cart_content self-pickup city_delivery_content">
                        <view class="city_delivery_content_left" style="width: 85%;">
                            <view class="left_top"> 立即配送，约10:32送达 </view>
                            <view class="left_bottom">商家等待您的下单</view>
                        </view>
                        <view class="city-delivery" style="width: 15%;">
                          <view class="city_delivery_pic" > <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/submitOrder.png" alt="" mode="widthFix"> </view>
                        </view>
                    </view>
                </template>
                <!-- 彩色的线 -->
                <view class="clearfix">
                    <img
                        src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/colorLine.png"
                        alt=""
                        style=" display:block; width: 100%; height:3px;" />
                </view>

                <view class="cartList">
                    <view class="goodsWraper clearfix" v-for="(item,index) in productList" :key="index" :id="item.Id">
                        <view class="wraper_left">
                            <view class="goodsPic">
                                <img class="img" :src="item.productUrl" mode="widthFix" />
                            </view>
                            <view class="goodsText">
                              <!-- <view > -->
                                <view class="goodsTop">
                                    <view class="goods_T">{{ item.productName }}</view>
                                    <view class="goods_price">X {{ item.cartNum }}</view>
                                </view>
                                <!-- <view class="goods_T">{{ item.title }}</view> -->
                                <view class="goods_specs" @click.stop="showSpecs()">{{ item.productAttrValueName }} </view>
                              <!-- </view> -->
                               
                                <view class="goodsBottom">
                                    <view class="money">￥{{ item.price }}</view>
                                    <view class="jifen_box"> <view class="money">最多可用</view>
                                        <img
                                            src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                            alt=""
                                            style="height: 22rpx; width: 22rpx; margin-right: 6px;margin-left: 6px;" />
                                        {{ item.maxUsefulIntegrals }}
                                    </view>
                                </view>
                            </view>
                        </view>
                        <!-- <view class="wraper_right">
                            <view class="shuliang"> X <span>{{ item.num }}</span> </view>
                        </view> -->

                    </view>

                </view>
                <!-- <view class="line_two" style="height: 5px;"></view> -->
                <!-- <view class="line"></view> -->
                <view class="price_detail clearfix">
                    <view class="price_detail_title">价格明细</view>
                    <!--  -->
                    <view class="price_detail_content">
                        <!-- 价格总额 -->
                        <view class="price_detail_box all">
                            <view class="price_detail_name">商品总额</view>
                            <view class="price_detail_num num">￥{{totalAmount}}</view>
                        </view>
                        <!-- 运费 -->
                        <view class="price_detail_box freightAmount">
                            <view class="price_detail_name">运费</view>
                            <view class="price_detail_num num" v-if="currentIndex===1">￥{{ freightAmount }}</view>
                            <view class="price_detail_text" v-if="currentIndex===0">免运费</view>

                        </view>
                        <!-- 优惠活动 -->
                        <view class="price_detail_box couponAct" v-if="totalThresholdAmount && totalThresholdAmount > 0 && totalFullDiscount>0">
                            <view class="price_detail_top">
                                <view class="price_detail_name">优惠活动</view>
                                <view class="price_detail_tips">满{{totalThresholdAmount}}减{{totalFullDiscount}}</view>
                            </view>
                            <!-- totalDiscount -->
                            <view class="price_detail_num num_o">- ￥{{ totalFullDiscount }}</view>
                        </view>
                        <!-- 优惠券 -->
                        <view class="price_detail_box coupon" v-if="ebStoreCouponList.length > 0">
                            <view class="price_detail_top">
                                <view class="price_detail_name">优惠券</view>
                                <view class="price_detail_tips"> {{defaultBestCoupon.money}}元{{ defaultBestCoupon.useType === 1? '全场通用券' : defaultBestCoupon.useType === 2? '商品券' : '品类券'  }}</view>
                            </view>
                            <view @click="openMyCoupon" class="price_detail_num num_o">-￥{{defaultBestCoupon.money}} <van-icon
                                name="arrow"
                                size="12"
                                style="margin-left:5px ;" /></view>
                        </view>
                    </view>
                    <!-- payment 支付方式 -->
                    <view class="payment">
                        <view class="payment_top">
                            <view class="payment_left price_detail_name">支付方式</view>
                            <view class="payment_right  price_detail_name" @click="openPayment(integralsBalance,orderMaxUsefulIntegrals)">支付
                              <span class="payment_num">
                               <span  v-if="shouldShowIntegrals"> <img
                                    src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                    alt=""
                                    style="height: 13px; width: 13px;margin-left: 11px; margin-right: 6px;"/>
                                {{ useIntegrals}}  </span> <span v-if="shouldShowPlus">+</span> <span v-if="shouldShowCash">￥{{ useCash }}</span></span>
                                <van-icon name="arrow" size="12" style="margin-left:5px ;"/>
                            </view>
                        </view>
                        <view class="payment_left_bottom price_detail_tips"> 我的积分:
                            <img
                                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/jinbi_gray1127.png"
                                alt=""
                                style="height: 10px; width: 10px;margin-left: 5px; margin-right: 5px;">
                            {{ integralsBalance }}
                        </view>
                    </view>
                    <!-- <view class="payment_num price_detail_name" @click="openPayment">支付
              <img
                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png" alt=""
                style="height: 13px; width: 13px;margin-left: 11px; margin-right: 6px;" />
                1520+¥262
                <van-icon  name="arrow" size="11" style="margin-left:5px ;" /></view>
          </view> -->
                </view>
                <view class="nav_box" style="height: 72px;">
                    <van-submit-bar
                        :price="allPrice"
                        button-text="提交订单"
                        @submit="onClickButton"
                        button-type="warning"
                        v-if="ebUserAddressList.length>0 && selfPickupName !== '' && selfPickupName !== undefined"  :disabled="isSubmitting" :class="{disabledSubmit:isSubmitting}">
                        <view class="footContent">
                            <view class="payment_num" style="line-height: 14px;"> <span v-if="shouldShowIntegrals"><img
                                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                alt=""
                                style="height: 13px; width: 13px; margin-right: 6px;" /> {{useIntegrals}}</span> <span v-if="shouldShowPlus">+</span> <span v-if="shouldShowCash"> ¥{{useCash}}</span></view>
                            <view class="price_detail_tips" style="line-height: 14px;" v-if="totalReductionAmount && totalReductionAmount > 0"> 共减￥ {{totalReductionAmount}}</view>
                        </view>
                    </van-submit-bar>
                    <van-submit-bar :price="allPrice" button-text="提交订单" disabled v-else class="disabledSubmit">
                        <view class="footContent">
                          <view class="payment_num" style="line-height: 14px;"> <span v-if="shouldShowIntegrals"><img
                                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                alt=""
                                style="height: 13px; width: 13px; margin-right: 6px;" /> {{useIntegrals}}</span> <span v-if="shouldShowPlus">+</span> <span v-if="shouldShowCash"> ¥{{useCash}}</span></view>
                            <view class="price_detail_tips" v-if="totalReductionAmount && totalReductionAmount > 0"> 共减￥{{totalReductionAmount}} </view>
                        </view>
                    </van-submit-bar>
                </view>
            </view>

        </scroll-view>
        <van-toast id="van-toast" />
        <myCoupon :show="myCouponShow" @closeCoupon="closeMyCoupon" @submitCoupon="submitCoupon" :ebStoreCouponResponse="ebStoreCouponResponse" :defaultBestCoupon="defaultBestCoupon"></myCoupon>
        <myHouse :show="myHouse" :house="house" @closeHouse="closeMyHouse" :pageBiaoshi="pageBiaoshi" :ebUserAddressList="ebUserAddressList" :wxUserBaseInfo="wxUserBaseInfo"></myHouse>
        <paymentPopup :show="paymentShow" @closePayment="closePayment" :needPayCashAmount="popupCash" :myIntegralsBalance="integralsBalance" :maxScore="orderMaxUsefulIntegrals" :exchangeRate="exchangeRate" @confirm="handlePaymentConfirm"></paymentPopup>
        <!-- <van-action-sheet
            :show="showHouseName"
            :actions="houseDataList"
            @click-overlay="overlayAddress"
            @cancel="onCloseAddress"
            @select="onSelectAddress"
            cancel-text="取消"
            :z-index="10000" /> -->
    <!-- </view> -->
    </view>
</template>

<script>
import Toast from '@/wxcomponents/vant/toast/toast'
import myCoupon from '@/mycomponents/myCoupon.vue'
import myHouse from '@/mycomponents/myHouse.vue'
import paymentPopup from '@/mycomponents/shangcheng/paymentPopup.vue'
import { SOURCE_TYPE } from '@/utils/constant'

import { getCartSettlementApi,getOrderFreightApi,creatOrderApi,getMerchantListApi,changeCouponAndGetResultApi,directBuyApi} from '@/api/shoppingCart'

export default {

    components: {
        myCoupon,
        myHouse,
        paymentPopup
    },
    name: 'Cart',
    data () {
        return {
            navBarTitle: '购物结算',
            scrolling: false, // 顶部区域吸顶效果
            wxUserBaseInfo:{},  //微信用户信息
            ebUserAddressList:[], //用户地址
            userAdderssDefault:null,  //用户默认地址
            houseName: '金鑫·滨湖一号3号楼1单元201',
            showHouseName: false, // 切换房子的列表
            myHouse: false,
            house: 0, // 有无房屋
            currentIndex: 0, // 配送方式的tab
            tabBarList: [
                {
                    name: '自提',
                    key: 'ziti'
                },
                {
                    name: '同城配送',
                    key: 'tongcheng'
                }
            ],
            userName: '王彤美',
            userTel: '15236236547',
            
            selfPickupName: '有',
            merchantList:[], //商户列表
            foundEleMerchant:null, //用户信息
            distance:undefined, //距离
            productInfoList:[], //提交商品信息列表
            productList: [
                // {
                //     Id: 11,
                //     imgurl: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/judge01.png',
                //     title: '黄芪杞姜枣糕红枣',
                //     current: '15',
                //     num: '1',
                //     score: 190,
                //     specs: '口味一：五斤装口味一：五斤装口味一：五斤装口味一：五斤装口味一：五斤装口味一：五斤装口味一：五斤装',
                //     isShouQing: false,
                //     isXiajia: false
                // },
                // {
                //     Id: 12,
                //     imgurl: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/judge01.png',
                //     title: '黄芪杞姜枣糕红枣枸杞 口味一：五斤装',
                //     current: '16',
                //     num: '1',
                //     score: 190,
                //     specs: '口味一：五斤装',
                //     isShouQing: false,
                //     isXiajia: false
                // },
                // {
                //     Id: 13,
                //     imgurl: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/judge01.png',
                //     title: '黄芪杞姜枣糕红枣枸杞 口味一：',
                //     current: '16',
                //     num: '3',
                //     score: 190,
                //     specs: '口味1：5斤装',
                //     isShouQing: false,
                //     isXiajia: false
                // }

            ],
            myCouponShow: false, // 优惠券弹窗
            ebStoreCouponResponse:{}, //优惠券信息
            ebStoreCouponList:[], //用户拥有的可用优惠券列表
            defaultBestCoupon:null, //默认最优优惠券
            paymentShow: false, // 支付方式选择弹窗
            freightAmount: '0',
            score: '0', // 需要支付的积分
            needPayCashAmount: '0', // 需要支付的金额            
            integralsBalance: '0', // 我的积分
            orderMaxUsefulIntegrals:"0", //订单最大可用积分数
            useIntegrals:'0', //实际使用积分
            useCash:'0', //实际使用的现金
            popupCash:'0', //弹出的现金
            frontCalAmount:'0', // 前计算金额
            usedCouponAmount:'0', //使用优惠券的金额
            totalAmount:undefined, //商品总额
            totalReductionAmount:undefined, //总减免金额
            pageBiaoshi:'cart',
            prouductIdList:undefined, //支付页面shangpinID  购物车ID列表
            totalThresholdAmount:undefined, //满多少 减多少  总满金额
            totalFullDiscount:undefined, //总减金额 （优惠的金额)）
            totalAdditionalAmount:undefined, //总凑得金额
            totalDiscount:undefined,
            nearestDistanceMap:undefined,
            loading:true,
            exchangeRate:'10', //兑换率
            productType:0, //商品类型 0 实物商品 1 服务商品
            payType:null, //支付方式// 现金支付 CASH("1"), // 积分支付 POINTS("2"), // 现金+积分支付 CASH_POINTS("3");
            productInfo:null,
            couponProductInfoList:null, //提交优惠券时商品信息列表
            productMatchedCouponInfo:null,// 商品匹配优惠券信息
            discountedAmount:'0',
            isSubmitting: false, // 新增防抖状态
            debounceTimer: null, // 防抖计时器
            params:null,
            source:undefined, // 从购物车页面跳转过来
        }
    },

  computed: {
    shouldShowIntegrals() {
      return Number(this.useIntegrals )> 0 && Number(this.integralsBalance) > 0;
    },
    shouldShowCash() {
      return this.useCash > 0;
    },
    shouldShowPlus() {
      return this.shouldShowIntegrals && this.shouldShowCash;
    },
    canSubmit() {
      return this.ebUserAddressList.length > 0 &&
        this.selfPickupName &&
        this.useCash >= 0 &&
        !isNaN(this.useCash);
    },
    numericMaxPoints() {
      return Math.min(
        Number(this.orderMaxUsefulIntegrals),
        Number(this.integralsBalance),
        Math.floor(Number(this.popupCash) * this.exchangeRate)
      );
    },
  },

    watch: {

    },
    onLoad(data){
       // 取到路由携带的参数
       if (data && data.params) {
            this.params = JSON.parse(decodeURIComponent(data.params))
            console.log(JSON.parse(decodeURIComponent(data.params)))
            console.log('params', this.params)
            this.prouductIdList = this.params.cartIds
            this.source = this.params.source || SOURCE_TYPE.DEFAULT
        }
      // const eventChannel = this.getOpenerEventChannel();
      // // 监听自提点更新事件
      // eventChannel.on('updateSelfPickup', (data) => {
      //   if (data.selectedMerchant) {
      //     this.selectedSelfPickup = data.selectedMerchant;
      //     // 这里可以添加更新UI的逻辑
      //     console.log('更新自提点',data.selectedMerchant)
      //   }
      // });
    },

    onReady () {
    // this.productList.forEach(item => {
    //     this.$set(item, 'isChecked', false)
    // })
    if(this.source === SOURCE_TYPE.CART){
        this.getCartSettlementData()
    }else if(this.source === SOURCE_TYPE.DETAIL){
      this.getDetailSettlementData()
    }
    },
    methods: {
      onClickLeft() {
        uni.navigateBack()
      },
      // 下拉选择框
      changeAddress(val) {
        this.house = val
        // this.showHouseName = true
        this.myHouse = true
      },
      // 提示
      toastMsg() {
        Toast('请先选择地址再进行结算')
      },

      closeMyHouse() {
        console.log('关闭 关闭关闭-------1111')
        this.myHouse = false
      },

      changeTab(index, e, itemName) {
        this.currentIndex = index
        console.log(index, itemName)
        // this.$emit('sliderSelect', index, itemName)
      },
      scrollPage(e) {
        console.log(e.detail.scrollTop, this.scrolling)
        if (e.detail.scrollTop > 25 && !this.scrolling) {
          this.scrolling = true
        } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
          this.scrolling = false
        }
      },

      // 优惠券
      openMyCoupon() {
        this.myCouponShow = true
      },
      closeMyCoupon() {
        this.myCouponShow = false
      },
      submitCoupon(selectedCpupon,isChange){
        console.log(selectedCpupon,'关闭优惠券',this.defaultBestCoupon,isChange)
        if(!isChange){
          return false
        }
        if(this.defaultBestCoupon.id !== selectedCpupon.couponId || this.defaultBestCoupon.couponId !==selectedCpupon.couponId){
          this.defaultBestCoupon = selectedCpupon
          const couponParams = {
            selectedCouponId:selectedCpupon.couponId,
            totalFullDiscount:this.totalFullDiscount,  //总满减金额
            productInfoList:this.couponProductInfoList,
            productMatchedCouponInfoList: this.transformCouponRelations()
          }
          console.log(couponParams,'优惠券参数')
          changeCouponAndGetResultApi(couponParams).then(res => {
            if (res.code === 200) {
              console.log(res,'changeCoupon')
              // this.getCartSettlementData()
              const changeCouponResponse = res.data
              this.needPayCashAmount = changeCouponResponse.needPayCashAmount || '0' //需要支付的金额
              this.frontCalAmount = changeCouponResponse.frontCalAmount || '0' //前端计算金额

              // this.useCash = this.needPayCashAmount
              this.useCash = this.needPayCashAmount == '0' ? this.frontCalAmount :  JSON.parse(JSON.stringify(this.needPayCashAmount))  //实际支付的现金

              this.useIntegrals = JSON.parse(JSON.stringify(this.orderMaxUsefulIntegrals)) || '0'
              this.totalReductionAmount = changeCouponResponse.totalReductionAmount
              this.usedCouponAmount = changeCouponResponse.usedCouponAmount
              this.productInfo.forEach((item, index) => {
                item.detailApportionCouponAmount=changeCouponResponse.couponDistributedAmountTable?.table[pid]?.[attrId] || '0',//明细优惠券优惠分摊的金额
                item.detailFinalActualAmount=changeCouponResponse.finalProductDetailAmountTable?.table[pid]?.[attrId] || '0' //终极版商品明细使用了多少金额
                item.detailUsedPoints= changeCouponResponse.productDeductAmountTable?.table[pid]?.[attrId] || '0', //明细使用积分
                item.detailPointsForCashAmount = item.detailUsedPoints * this.exchangeRate //明细使用积分抵现的金额
              })
            }
          })
        }
      },
      // 新增转换方法 获取商品拼配的优惠券id
      transformCouponRelations() {
        const table = this.ebStoreCouponResponse.productAndCouponIdTable.table || {}
        return Object.entries(table).flatMap(([productId, attrs]) =>

          Object.entries(attrs).map(([attrValueId, couponIds]) => ({
            productId: parseInt(productId),
            productAttrValueId: parseInt(attrValueId),
            couponIdList: Array.isArray(couponIds) ? couponIds : []
          }))
        )
      },

      // 支付方式
      openPayment(integralsBalance,orderMaxUsefulIntegrals) {
        console.log(this.shouldShowIntegrals)
        if (!this.shouldShowIntegrals) {
          if(integralsBalance == '0'){
            Toast('您的积分不足')
          }
          if(orderMaxUsefulIntegrals == '0'){
            Toast('该订单最大可使用积分为0')
          }
          return false
        }
        this.paymentShow = true
      },


      closePayment() {
        this.paymentShow = false
      },

      // 跳转自提点选择页面
      toSelectPick() {
        // 确保已获取有效地址ID
        const addressId = this.userAdderssDefault?.id;
        if (!addressId) {
          Toast('请先选择收货地址');
          return;
        }
        const params = {
          userAdderssDefault: this.userAdderssDefault,
          addressId: addressId,
          foundEleMerchant: this.foundEleMerchant,
          distance: this.distance,
        }
        uni.navigateTo({
          url:
            '/pages/shoppingCart/selfPickupPoint?params=' +
            encodeURIComponent(JSON.stringify(params))
        })
      },


      // 提交订单 跳转收银页面
      async onClickButton() {
          if (this.isSubmitting) {
            Toast('订单正在提交中，请勿重复提交');
            return Promise.reject('重复提交'); // 确保后续代码不会执行
          }
          clearTimeout(this.debounceTimer);
          // 防抖锁定
          this.isSubmitting = true;
    
          try {
            this.debounceTimer = setTimeout(() => {
              this.isSubmitting = false;
            }, 3000); // 3秒后自动解锁防止死锁

            // 支付类型校验逻辑
            if (this.useIntegrals == '0' && this.useCash == '0') {
              Toast('请选择支付方式');
              return;
            }
            // 自动推导支付类型（如果用户未显式选择）
            if (!this.payType) {
              this.selectPayType()  // 自动推导支付类型（如果用户未显式选择）
            }
            // 在跳转前添加支付方式验证
            if (!['1', '2', '3'].includes(this.payType)) {
              Toast('请选择有效的支付方式');
              return;
            }

            const apiParams = {
              requestSource: this.source, //请求来源
              wxUserId: this.wxUserBaseInfo.id, //微信用户id
              addressId: this.userAdderssDefault.id,//地址id
              productInfoList: this.productInfo,//商品信息
              cartIdList: this.source === SOURCE_TYPE.CART ? this.prouductIdList :undefined, //购物车id列表  被选中的
              productType: this.productType, //商品类型
              totalAmount: this.totalAmount, //商品总额
              discountedAmount: this.totalFullDiscount, //优惠活动优惠金额  总满减金额
              couponAmount: this.defaultBestCoupon?.money || null, //优惠券优惠金额
              couponId: this.defaultBestCoupon?.id || null, //使用的优惠券id
              selfPickId: this.foundEleMerchant.id, //自提点id
              actualAmount: this.useCash, //实际支付金额
              actualPoints: this.useIntegrals, //实际支付积分
              freightAmount: this.freightAmount, //运费金额
              shippingType: this.currentIndex == 0 ? '1' : '2',  //配送方式
              payType: this.payType,  //支付方式
            }
            console.log('提交订单', apiParams)
            const res = await creatOrderApi(apiParams)
            if (res.code === 200) {
              // 成功提交后立即解锁
              clearTimeout(this.debounceTimer);
              this.isSubmitting = false;
              Toast('下单成功，请支付')
              const params = {}
              params.pageSymbol = 'goods'
              params.orderId = res.data.orderId  //订单id
              params.totalAmount = res.data.payAmount  //订单需支付总金额
              params.orderNo = res.data.orderNo  //订单号
              params.source = this.source
              uni.redirectTo({
                url:
                  '/pages/payment/cashPage?params=' +
                  encodeURIComponent(JSON.stringify(params))
              })
            }
          } catch (error) {
            Toast('提交失败，请重试');
          } finally {
            clearTimeout(this.debounceTimer);
            this.isSubmitting = false;
          }
      },

      //导航 地图
      toMap(foundEleMerchant) {
        if (!foundEleMerchant || !this.userAdderssDefault) {
          Toast('商户信息未加载完成');
          return;
        }
        const params = {
          merchantLocation: {
            latitude: foundEleMerchant.latitude,
            longitude: foundEleMerchant.longitude
          },
          userLocation: {
            latitude: this.userAdderssDefault.latitude,
            longitude: this.userAdderssDefault.longitude
          }
        }
        uni.navigateTo({
          url:
            '/pages/shoppingCart/map?params=' +
            encodeURIComponent(JSON.stringify(params))
        })
      },
      //处理地址
      async processAddressInfo(wxUserBaseInfo) {
          this.wxUserBaseInfo = wxUserBaseInfo || {};
          this.ebUserAddressList = this.wxUserBaseInfo.ebUserAddressList || [];

          if (this.ebUserAddressList.length > 0) {
            this.userAdderssDefault = this.ebUserAddressList.find(ele => ele.isDefault) || this.ebUserAddressList[0];
            const addressId = this.userAdderssDefault?.id;
            if (addressId) {
              await this.getMerchantList(addressId)
            }
          }
          this.foundEleMerchant = this.merchantList[0] || null;
          console.log('最终商户数据:', this.foundEleMerchant);
      },

      // 处理商品信息 提交订单时需要的商品信息
      async processProductInfo(responseData) {
        const integralsResponse = responseData?.ebStoreIntegralsResponse || {};
        const fullDiscountMatchedResponse = responseData.fullDiscountMatchedResponse || {};
        const info = JSON.parse(JSON.stringify(this.productInfoList))
          // 映射关键字段到productInfo
          this.productInfo = info.map(item => {
              // 将字符串类型转换为数字类型匹配接口数据
              const pid = item.productId
              const attrId = item.productAttrValueId

                return {
                  productId: pid,           // 商品ID
                  productName: item.productName,
                  productImageUrl: item.productUrl,
                  // productImageUrl: item.productAttrValueList?.find(
                  //   attr => attr.id === item.productAttrValueId
                  // )?.image || item.productUrl, // 商品对应规格图片
                  // productType:item.seckillId,  //商品类型
                  productAttrValueId: attrId, // 规格ID
                  skuName: item.skuName,
                  quantity: item.cartNum,
                  // storeKind:item.seckillId,
                  categoryIdList: item.categoryIdList,

                  detailUsedPoints: integralsResponse.productActualUsedPointsTable?.table[pid]?.[attrId] || '0', //明细使用积分
                  detailPointsForCashAmount: integralsResponse.productDeductAmountTable?.table[pid]?.[attrId] || '0', //明细使用积分抵现的金额
                  originalityDetailAmount: item.price,  //明细消费原始的金额
                  detailApportionFullDiscountAmount: (fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
                    .find(d =>
                      d.productId === pid &&
                      d.productAttrValueId === attrId
                    )?.bestDiscount || '0', //明细满减活动分摊的金额
                  // detailApportionFullDiscountAmount: fullDiscountMatchedResponse.bestDiscount || '0', //明细满减活动分摊的金额
                  detailFullDiscountId:  (fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
                    .find(d =>
                      d.productId === pid &&
                      d.productAttrValueId === attrId
                    )?.bestFullDiscount.id || null, //明细使用的满减ID
                  detailApportionCouponAmount: this.ebStoreCouponResponse.couponApportionmentAmountTable?.table[pid]?.[attrId] || '0', //明细优惠券优惠分摊的金额
                  detailFinalActualAmount: integralsResponse.finalProductDetailAmountTable?.table[pid]?.[attrId] || '0', //终极版商品明细使用了多少金额
                }
              }
            )
            console.log(this.productInfo, 'productInfo')
      },
      processPaymentInfo(responseData) {
          // 支付基础信息
          this.needPayCashAmount = responseData.needPayCashAmount ?? '0' // 需要付的现金
          this.frontCalAmount = responseData.frontCalAmount ?? '0' //前端计算金额
          this.integralsBalance = responseData.integralsBalance ?? '0'// 我的账户余额
          this.exchangeRate = responseData.pointsRatio ?? '0'  //兑换率
          this.totalAmount = responseData.totalAmount ?? '0' //商品总金额


          // 积分计算
          this.orderMaxUsefulIntegrals = responseData?.ebStoreIntegralsResponse?.orderMaxUsefulIntegrals ?? 0  //订单最大可用积分数
          const usePoints = this.orderMaxUsefulIntegrals > 0 ? (this.integralsBalance >0 && this.integralsBalance < this.orderMaxUsefulIntegrals? this.integralsBalance : this.orderMaxUsefulIntegrals):0
          this.useIntegrals = this.needPayCashAmount == '0' ? this.frontCalAmount * this.exchangeRate :usePoints //实际使用积分数
         
          this.useCash = JSON.parse(JSON.stringify(this.needPayCashAmount));
          this.popupCash = this.needPayCashAmount == '0' ? this.frontCalAmount : this.useCash;

          // 优惠信息
          this.totalReductionAmount = responseData.totalReductionAmount ?? '0'  //总减免金额
          const integralsResponse = res.data.response?.ebStoreIntegralsResponse ?? {}  //积分以及分摊信息
          const fullDiscountMatchedResponse = responseData.fullDiscountMatchedResponse  //满减以及分摊信息
          // this.totalDiscount = fullDiscountMatchedResponse.totalDiscount || '0'  //满减减得部分
          // this.totalDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0'  //满减减得部分
          this.totalThresholdAmount = fullDiscountMatchedResponse.totalThresholdAmount || null
          this.totalFullDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0' //总满减金额

      },
      processProductList(){},
      // 公共处理方法
      async processSettlementData(data) {
          const responseData = data.response;
          const wxUserBaseInfo = data.wxUserBaseInfo;
          
          // 处理商品列表
          this.processProductList(responseData);
          
          // 处理支付信息
          this.processPaymentInfo(responseData);
          
          // 处理地址信息
          await this.processAddressInfo(wxUserBaseInfo)
          
          // 处理商品详细信息
          this.processProductDetails(responseData);
      },

      /** 
       * 接口测试
       *  */
      async getCartSettlementData() {
        this.loading = true
        try {
          const res = await getCartSettlementApi();
          if (res.code === 200) {
            this.loading = false
            console.log(res.data, 'res')
            const responseData = res.data.response
            this.productInfoList = JSON.parse(JSON.stringify(responseData.productAndAttrResponse.responseList))
            this.productList = JSON.parse(JSON.stringify(this.productInfoList))
            this.productList.forEach(item => {
              let productAttrValueName = ''
              let productStock = ''
              // 使用 find 方法找到满足条件的元素
              const foundEle = item.productAttrValueList.find(ele => ele.id === item.productAttrValueId);
              console.log(foundEle, 'foundEle')
              if (foundEle) {
                if(foundEle.suk !==''){
                  productAttrValueName = foundEle.suk  //规格名称
                }else{
                  productAttrValueName = '默认' //规格名称
                }
                // productAttrValueName = foundEle.suk  //规格名称
                productStock = foundEle.stock  //规格库存
              }
              item.productAttrValueName = productAttrValueName;
              item.productStock = productStock
            })

            this.needPayCashAmount = responseData.needPayCashAmount ?? '0' // 需要付的现金
            this.frontCalAmount = responseData.frontCalAmount ?? '0' //前端计算金额
            this.integralsBalance = responseData.integralsBalance ?? '0'// 我的账户余额
            this.exchangeRate = responseData.pointsRatio ?? '0'  //兑换率
            this.totalAmount = responseData.totalAmount ?? '0' //商品总金额

            this.orderMaxUsefulIntegrals = responseData?.ebStoreIntegralsResponse?.orderMaxUsefulIntegrals ?? 0  //订单最大可用积分数
            const usePoints = this.orderMaxUsefulIntegrals > 0 ? (this.integralsBalance >0 && this.integralsBalance < this.orderMaxUsefulIntegrals? this.integralsBalance : this.orderMaxUsefulIntegrals):0
            this.useIntegrals = this.needPayCashAmount == '0' ? this.frontCalAmount * this.exchangeRate :usePoints //实际使用积分数

            // this.useIntegrals = this.needPayCashAmount == '0' ? this.frontCalAmount * this.exchangeRate :0  //实际使用积分数  以前的
          
            this.useCash = JSON.parse(JSON.stringify(this.needPayCashAmount))  //实际支付的现金
            this.popupCash = this.needPayCashAmount == '0' ? this.frontCalAmount :  JSON.parse(JSON.stringify(this.needPayCashAmount))  //实际支付的现金

            this.totalReductionAmount = responseData.totalReductionAmount ?? '0'  //总减免金额
            const integralsResponse = res.data.response?.ebStoreIntegralsResponse ?? {}  //积分以及分摊信息
            const fullDiscountMatchedResponse = responseData.fullDiscountMatchedResponse  //满减以及分摊信息
            // this.totalDiscount = fullDiscountMatchedResponse.totalDiscount || '0'  //满减减得部分
            // this.totalDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0'  //满减减得部分
            this.totalThresholdAmount = fullDiscountMatchedResponse.totalThresholdAmount || null
            this.totalFullDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0' //总满减金额

            this.ebStoreCouponResponse = responseData.ebStoreCouponResponse || {} //优惠券信息（可用优惠券+不可用优惠券）
            this.ebStoreCouponList = this.ebStoreCouponResponse?.availableCouponList || [] //用户拥有的可用优惠券列表
            this.defaultBestCoupon = this.ebStoreCouponResponse?.defalutBestEbStoreCoupon || null //默认最优优惠券


            this.nearestDistanceMap = res.data.nearestDistanceMap || undefined //距离信息
            this.wxUserBaseInfo = res.data?.wxUserBaseInfo || {}  //微信用户基础信息
            this.ebUserAddressList = this.wxUserBaseInfo.ebUserAddressList || []  //用户地址
            if(this.ebUserAddressList.length > 0){
              this.userAdderssDefault = this.ebUserAddressList.find(ele => ele.isDefault === true) || this.ebUserAddressList[0]  //默认的用户地址
            }
            const addressId = this.userAdderssDefault?.id;  //地址id
            if (addressId) {
              await this.getMerchantList(addressId)
            }
            // 使用接口返回的最新商户数据
            this.foundEleMerchant = this.merchantList[0] || null;
            console.log('最终商户数据:', this.foundEleMerchant);
  
            const info = JSON.parse(JSON.stringify(this.productInfoList))
            // 映射关键字段到productInfo
            this.productInfo = info.map(item => {
              // 将字符串类型转换为数字类型匹配接口数据
              const pid = item.productId
              const attrId = item.productAttrValueId

                return {
                  productId: item.productId,           // 商品ID
                  productName: item.productName,
                  productImageUrl: item.productUrl,
                  // productImageUrl: item.productAttrValueList?.find(
                  //   attr => attr.id === item.productAttrValueId
                  // )?.image || item.productUrl, // 商品对应规格图片
                  // productType:item.seckillId,  //商品类型
                  productAttrValueId: item.productAttrValueId, // 规格ID
                  skuName: item.skuName,
                  quantity: item.cartNum,
                  // storeKind:item.seckillId,
                  categoryIdList: item.categoryIdList,

                  detailUsedPoints: integralsResponse.productActualUsedPointsTable?.table[pid]?.[attrId] || '0', //明细使用积分
                  detailPointsForCashAmount: integralsResponse.productDeductAmountTable?.table[pid]?.[attrId] || '0', //明细使用积分抵现的金额
                  originalityDetailAmount: item.price,  //明细消费原始的金额
                  detailApportionFullDiscountAmount: (fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
                    .find(d =>
                      d.productId === pid &&
                      d.productAttrValueId === attrId
                    )?.bestDiscount || '0', //明细满减活动分摊的金额
                  // detailApportionFullDiscountAmount: fullDiscountMatchedResponse.bestDiscount || '0', //明细满减活动分摊的金额
                  detailFullDiscountId:  (fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
                    .find(d =>
                      d.productId === pid &&
                      d.productAttrValueId === attrId
                    )?.bestFullDiscount.id || null, //明细使用的满减ID
                  detailApportionCouponAmount: this.ebStoreCouponResponse.couponApportionmentAmountTable?.table[pid]?.[attrId] || '0', //明细优惠券优惠分摊的金额
                  detailFinalActualAmount: integralsResponse.finalProductDetailAmountTable?.table[pid]?.[attrId] || '0', //终极版商品明细使用了多少金额
                }
              }
            )
            console.log(this.productInfo, 'productInfo')
            this.couponProductInfoList = info.map(({productId, productAttrValueId, cartNum }) => ({
                productId: productId,           // 商品ID
                productAttrValueId:productAttrValueId, // 规格ID
                num: cartNum,
                afterFullDiscountProductAmount: fullDiscountMatchedResponse.afterFullDiscountProductAmountsTable?.table[productId]?.[productAttrValueId] || '0', //终极版商品明细使用了多少金额
            }) )

          }
        } catch (error) {
          console.error('获取数据失败:', error);
        } finally {
          this.loading = false;
        }
      },

      // 商品详情页面 -- 立即购买
      async getDetailSettlementData() {
        this.loading = true
        try {
          const pa = {
            productId: this.params.productId,
            productAttrValueId: this.params.productAttrValueId,
            buyNum: this.params.buyNum
          }
          console.log(pa,'pa')
          const res = await directBuyApi(pa);
          if (res.code === 200) {
            this.loading = false
            console.log(res.data, 'res')
            const responseData = res.data.response
            this.productInfoList = JSON.parse(JSON.stringify(responseData.productAndAttrResponse.responseList))
            this.productList = JSON.parse(JSON.stringify(this.productInfoList))
            this.productList.forEach(item => {
              let productAttrValueName = ''
              let productStock = ''
              // 使用 find 方法找到满足条件的元素
              const foundEle = item.productAttrValueList.find(ele => ele.id === item.productAttrValueId);
              console.log(foundEle, 'foundEle')
              if (foundEle) {
                if(foundEle.suk !==''){
                  productAttrValueName = foundEle.suk  //规格名称
                }else{
                  productAttrValueName = item.skuName || '默认' //规格名称
                }
                productStock = foundEle.stock  //规格库存

                // productAttrValueName = foundEle.suk  //规格名称
                // productStock = foundEle.stock  //规格库存
              }
              item.productAttrValueName = productAttrValueName;
              item.productStock = productStock
            })

            this.needPayCashAmount = responseData.needPayCashAmount || '0' // 需要付的现金
            this.frontCalAmount = responseData.frontCalAmount || '0' //前端计算金额
            this.integralsBalance = responseData.integralsBalance || '0' // 我的账户余额
            this.exchangeRate = responseData.pointsRatio || '0'  //兑换率
            this.totalAmount = responseData.totalAmount || '0'  //商品总金额
            this.orderMaxUsefulIntegrals = responseData.ebStoreIntegralsResponse?.orderMaxUsefulIntegrals ?? 0    //订单最大可用积分数
            console.log(this.orderMaxUsefulIntegrals,'订单最大可用积分数')
            const usePoints = this.orderMaxUsefulIntegrals > 0 ? (this.integralsBalance >0 && this.integralsBalance < this.orderMaxUsefulIntegrals? this.integralsBalance : this.orderMaxUsefulIntegrals):0
            this.useIntegrals = this.needPayCashAmount == '0' ? this.frontCalAmount * this.exchangeRate :usePoints //实际使用积分数 
            this.useCash = JSON.parse(JSON.stringify(this.needPayCashAmount))  //实际支付的现金
            this.popupCash = this.needPayCashAmount == '0' ? this.frontCalAmount :  JSON.parse(JSON.stringify(this.needPayCashAmount))  //实际支付的现金

            this.totalReductionAmount = responseData.totalReductionAmount  || '0'  //总减免金额
            const integralsResponse = responseData?.ebStoreIntegralsResponse || {}  //积分以及分摊信息
            const fullDiscountMatchedResponse = responseData.fullDiscountMatchedResponse  //满减以及分摊信息
            // this.totalDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0'  //满减减得部分
            this.totalThresholdAmount = fullDiscountMatchedResponse.totalThresholdAmount || null
            this.totalFullDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0' //总满减金额

            this.ebStoreCouponResponse = responseData.ebStoreCouponResponse || {} //优惠券信息（可用优惠券+不可用优惠券）
            this.ebStoreCouponList = this.ebStoreCouponResponse?.availableCouponList || [] //用户拥有的可用优惠券列表
            this.defaultBestCoupon = this.ebStoreCouponResponse?.defalutBestEbStoreCoupon || null //默认最优优惠券


            this.nearestDistanceMap = res.data.nearestDistanceMap || undefined //距离信息
            this.wxUserBaseInfo = res.data?.wxUserBaseInfo || {}  //微信用户基础信息
            this.ebUserAddressList = this.wxUserBaseInfo.ebUserAddressList || []  //用户地址
            if(this.ebUserAddressList.length > 0){
              this.userAdderssDefault = this.ebUserAddressList.find(ele => ele.isDefault === true) || this.ebUserAddressList[0]  //默认的用户地址
            }
            const addressId = this.userAdderssDefault?.id;  //地址id
            if (addressId) {
              await this.getMerchantList(addressId)
            }
            // 使用接口返回的最新商户数据
            this.foundEleMerchant = this.merchantList[0] || null;
            console.log('最终商户数据:', this.foundEleMerchant);
  
            const info = JSON.parse(JSON.stringify(this.productInfoList))
            // 映射关键字段到productInfo
            this.productInfo = info.map(item => {
              // 将字符串类型转换为数字类型匹配接口数据
              const pid = item.productId
              const attrId = item.productAttrValueId

                return {
                  productId: item.productId,           // 商品ID
                  productName: item.productName,
                  productImageUrl: item.productUrl,
                  // productImageUrl: item.productAttrValueList?.find(
                  //   attr => attr.id === item.productAttrValueId
                  // )?.image || item.productUrl,
                  // productType:item.seckillId,  //商品类型
                  productAttrValueId: item.productAttrValueId, // 规格ID
                  skuName: item.skuName,
                  quantity: item.cartNum,
                  // storeKind:item.seckillId,
                  categoryIdList: item.categoryIdList,

                  detailUsedPoints: integralsResponse.productActualUsedPointsTable?.table[pid]?.[attrId] || '0', //明细使用积分
                  detailPointsForCashAmount: integralsResponse.productDeductAmountTable?.table[pid]?.[attrId] || '0', //明细使用积分抵现的金额
                  originalityDetailAmount: item.price,  //明细消费原始的金额
                  detailApportionFullDiscountAmount: (fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
                    .find(d =>
                      d.productId === pid &&
                      d.productAttrValueId === attrId
                    )?.bestDiscount || '0', //明细满减活动分摊的金额
                  detailFullDiscountId:  (fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
                    .find(d =>
                      d.productId === pid &&
                      d.productAttrValueId === attrId
                    )?.bestFullDiscount.id || null, //明细使用的满减ID
                  // detailApportionFullDiscountAmount: fullDiscountMatchedResponse.bestDiscount || '0', //明细满减活动分摊的金额
                  // detailFullDiscountId: null, //明细使用的满减ID
                  detailApportionCouponAmount: this.ebStoreCouponResponse.couponApportionmentAmountTable?.table[pid]?.[attrId] || '0', //明细优惠券优惠分摊的金额
                  detailFinalActualAmount: integralsResponse.finalProductDetailAmountTable?.table[pid]?.[attrId] || '0', //终极版商品明细使用了多少金额
                  // detailFinalActualAmount: fullDiscountMatchedResponse.afterFullDiscountProductAmountsTable?.table[pid]?.[attrId] || '0', //终极版商品明细使用了多少金额
                }
              }
            )
            console.log(this.productInfo, 'productInfo')
            this.couponProductInfoList = info.map(({productId, productAttrValueId, cartNum }) => ({
                productId: productId,           // 商品ID
                productAttrValueId:productAttrValueId, // 规格ID
                num: cartNum,
                afterFullDiscountProductAmount: fullDiscountMatchedResponse.afterFullDiscountProductAmountsTable?.table[productId]?.[productAttrValueId] || '0', //终极版商品明细使用了多少金额
            }) )

          }
        } catch (error) {
          console.error('获取数据失败:', error);
        } finally {
          this.loading = false;
        }
      },

      // 获取订单运费
      getOrderFreight(orderId) {
        getOrderFreightApi(orderId).then(res => {
          if (res.code === 200) {

          }
        })
      },

      // 获取商户信息列表
      async getMerchantList(addressId) {
        if (!addressId) {
          console.error('缺少地址ID');
          return;
        }
        try {
          const res = await getMerchantListApi({ pageSize: 10, pageNum: 1, addressId: addressId })
          if (res.code === 200) {
            this.merchantList = res.data.merchantList || [] //商户列表

            this.foundEleMerchant = this.merchantList[0] || null//推荐的自提点
            console.log(this.foundEleMerchant, 'foundEleMerchant')
            const dis = res.data.distance
            this.distance = dis > 1000 ? `${(dis / 1000).toFixed(2)}公里` : `${dis}米`
            //  const dis = Number(res.data.distance) || 0
            //  this.distance = dis >= 1000 ?  `${(dis / 1000).toFixed(dis%1000 === 0 ? 0 : 2)}公里` :  `${Math.round(dis)}米`
          }
        } catch (error) {
          console.error('获取商户失败:', error);
          this.foundEleMerchant = null;
        }
      },


      //确认支付方式        
      handlePaymentConfirm(data) {
        console.log('支付方式:', data.type)
        console.log('使用积分:', data.score)
        console.log('需付现金:', data.cash)

        // 积分分摊逻辑
        // 将 data.score 转换为数字类型，如果 data.score 不是有效的数字，则默认为 0
        const totalPoints = Number(data.score) || 0
        // 计算所有商品的折扣后总金额
        const totalAmount = this.productInfo.reduce((sum, item) => sum + item.afterDiscountAmount, 0)
        // 初始化剩余积分，初始值为总积分
        let remainingPoints = totalPoints
        // 遍历每个商品信息
        this.productInfo.forEach((item, index) => {
          // 最后一个商品使用尾插法处理剩余积分
          if (index === this.productInfo.length - 1) {
            // 将剩余的积分全部分配给最后一个商品
            item.detailUsedPoints = remainingPoints
            // 根据积分兑换率计算该商品使用积分可抵扣的现金金额
            item.detailPointsForCashAmount = item.detailUsedPoints / this.exchangeRate
          } else {
            // 按比例分配积分
            // 计算当前商品的折扣后金额占总金额的比例
            const ratio = item.afterDiscountAmount / totalAmount;
            // 按比例分配积分给当前商品，并向下取整
            item.detailUsedPoints = Math.floor(totalPoints * ratio);
            // 减去已分配给当前商品的积分，更新剩余积分
            remainingPoints -= item.detailUsedPoints;
            // 根据积分兑换率计算该商品使用积分可抵扣的现金金额
            item.detailPointsForCashAmount = item.detailUsedPoints / this.exchangeRate
          }
        })

        // 提交支付请求...
        this.useIntegrals = data.score
        this.useCash = data.cash
        // 确保金额不会出现负数
        if (this.useCash < 0) {
          this.useCash = 0;
          Toast('支付金额异常，已重置为纯现金支付');
        }

        this.selectPayType()
      },

      // 积分划分（未选择支付方式时）
      integralsDivision() {
        // 自动分配积分逻辑
        if (!this.payType) {
          // 取三者最小值：积分余额、订单最大积分、现金换算积分
          const maxIntegrals = Math.min(
            this.integralsBalance,
            this.orderMaxUsefulIntegrals,
            Math.floor(this.popupCash * this.exchangeRate)
          );

          this.useIntegrals = maxIntegrals;  //最大可兑换积分
          this.useCash = this.needPayCashAmount == '0'?  this.needPayCashAmount:( this.needPayCashAmount - (maxIntegrals / this.exchangeRate))

          // 确保现金不为负数
          if (this.useCash < 0) {
            this.useCash = 0;
            this.useIntegrals = Math.floor(this.needPayCashAmount * this.exchangeRate);
          }

          // 自动设置支付类型
          this.selectPayType()
        }
      },

      selectPayType() {
        // 自动设置支付类型
        if (this.useIntegrals == '0') {
          this.payType = '1' // 'cash'
        } else if (this.useCash == '0') {
          this.payType = '2'  // 'point'
        } else if (this.useIntegrals > 0 && this.useCash > 0) {
          this.payType = '3' // 'cash_point'
        }
      },



      formatNumber(value) {
        return Number(value).toLocaleString();
      },
      formatCurrency(value) {
        return Number(value).toFixed(2);
      },

    }

}
</script>
<style lang="scss" scoped>

.content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    height: 100vh;
    overflow: hidden;
    z-index: -2;
    background-color: #FFFFFF;
}

.bgCart{
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #f9f9f9;
  height: 100vh;
  // height: calc(100vh - 70px);
  
  // padding-bottom: 200px;
}

// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}
.cartTop {
  background-color: #ffffff;
  padding-left: 24px;
  padding-right: 24px;
  padding-top: 25px;

  // 页面标题部分
  .cartAd {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .cartAd_title {
    font-size: 30px;
    text-align: left;
    line-height: 30px;
    color: #111111;
  }
  .userInfo{
    margin-top: 25px;
    display: flex;
    justify-content: space-between;
    padding-bottom: 23px;

  }
  .userInfo_left{   //左边用户信息
    display: flex;
    flex-direction: column;
    justify-content: space-between;
   width: 68%;
    
  }
  // .user_address{  //住址
  //   font-size: 14px;
  //   text-align: left;
  //   color: #737373;
  //   white-space: nowrap;
  // }
  // .user_address text{
  //   white-space: nowrap;
  //   /* 防止文本换行 */
  //   overflow: hidden;
  //   /* 超出部分隐藏 */
  //   text-overflow: ellipsis;
  //   /* 显示省略号 */
  // }
    .user_address {
      //住址
      font-size: 28rpx;
      text-align: left;
      color: #737373;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  
    .user_address_text {
      max-width: 90%;
      white-space: nowrap;
      /* 防止文本换行 */
      overflow: hidden;
      /* 超出部分隐藏 */
      text-overflow: ellipsis;
      /* 显示省略号 */
    }
  .userInfo_bottom{
    // font-weight: bolder;
    font-size: 14px;
    text-align: left;
    color: #737373;
    line-height: 14px;
    margin-top: 13px;

  }
  .userInfo_right{
    float: right;
    text-align: right;
  }

}

// 配送方方式
.tab-bar{
    padding:0px 2px;
    // width: 112px;
    height: 20px;
    background: #F0F0F0;
    // border: 1px solid rgba(255, 255, 255, 0.6);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
}

// 日月周统计
// .white {
//   .tabbar-item {
//     flex: auto;
//     z-index: 1;
//     width: 36px;
//     height: 28px;
//     line-height: 28px;
//     text-align: center;
//     font-size: 14px;
//     font-weight: 400;
//     color: #242629;

//     &.active {
//       background: #FFFFFF;
//       box-shadow: 0px 2px 5px rgba(61, 92, 153, 0.1);
//       border-radius: 6px;
//       font-style: normal;
//       font-weight: bold;
//       color: #242629;
//     }
//   }
// }

//自提  同城配送
.gray{
  // padding:2px;
  height: 20px;
  border-radius: 10px;
  .tabbar-item {
    flex: auto;
    z-index: 1;
    height: 20px;
    line-height: 20px;
    text-align: center;
    padding: 0px 3px;
    font-size: 12px;
    // font-weight: 500;
    color: #111111;

    &.active {
      background: #FF6203;
      border-radius: 10px;
      padding: 0px 18rpx;
      // padding: 0px 18px;
      color: #ffffff;
    //    &.option{
    //    font-weight: bold;
    //    background: #FFECE8;
    //    border-radius: 6px;
    //    color: #F54545;
    // }
    // &.state{
    //   color:#FA8537;
    //   background: #FFF5E8;
    // }
    }

  }
}

// 标题下面的横线
.line {
  height: 9px;
  width: 100%;
  background: #f9f9f9;
  // margin-top: 26px;
  // margin-bottom: 26px;
}

// 自提点
.self-pickup{
  margin-top: 10px;
  padding: 24px;
  background-color:#FFFFFF;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
// 有自提点的内容
.self-pickup-left{
  width: 75%;
  display: flex;
  // align-items: center;

  .self_pickup_pic{
    width: 20%;
    display: flex;
    flex-direction: column;
    justify-content: center;

    img{
      width: 100%;
        height: auto;
    }
  }

  // 图片右边的文字
    .self_pickup_left_l {
      display: flex;
      flex-direction: column;
      justify-content: center;
      width: 70%;
      margin-left: 15px;

      .left_top {
        // flex: auto;
        font-size: 28rpx;
        text-align: left;

        .self_pickup_name {
          // color: #737373;
          color: #111111;
          margin-right: 7px;
        }

        .distance {
          color: #FF6203;
        }
      }

      .left_bottom {
        margin-top: 20rpx;
        // flex: auto;
        font-size: 22rpx;
        text-align: left;
        color: #737373 ;
      }
    }

}

.self-pickup-right {
  display: flex;

  .spr_text {
    margin-left: 16rpx;
    font-size: 22rpx;
    text-align: left;
    color: #888888;
  }
}
// 无自提点
.no-self-pickup{
  font-weight: bolder;
  font-size:28rpx;
  text-align: left;
  color: #FF6203;
}

// 同城配送
.city_delivery_content {
    display: flex;
    align-items: center;

    .city_delivery_content_left {
        display: flex;
        // justify-content: space-between;
        flex-direction: column;

        .left_top {
            // flex: auto;
            font-size: 28rpx;
            line-height: 28rpx;
            text-align: left;
        }

        .left_bottom {
            font-size: 22rpx;
            line-height: 22rpx;
            text-align: left;
            color: #737373;
            margin-top: 22rpx;
        }
    }

    .city-delivery {
        .city_delivery_pic {
            width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;

            img {
                width: 100%;
                height: auto;
            }
        }
    }
}

.cartList{
  padding: 24px;
  width: calc(100% - 48px);
  background-color: #ffffff;
}

.goodsWraper {
  display: flex;
  justify-content: space-between;
  // align-items: center;
  width: 100%;
  margin-bottom: 15px;
}
.goodsWraper:last-child{
  margin-bottom: 0px;
}

.wraper_left {
  display: flex;
  // width: 90%;
  width: 100%;

  .goodsPic {
    width: 27%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    img {
      width: 100%;
      height: auto;
    }
  }

  .goodsText {
    // width: 68%;
    // margin-left: 10px;
    width: calc(73% - 20rpx);
    padding-left: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding-top: 12rpx;
    padding-bottom: 12rpx;
    text-align: left;

    // .goods_T {
    //   // position: absolute;
    //   // top: 2%;
    //   font-size: 14px;
    //   text-align: left;
    //   color: #111111;
    //   line-height: 14px;
    //   // margin-top: 9px;  //display：flex   中 元素居中
    //   max-width: 100%;
    //   white-space: nowrap;
    //   /* 防止文本换行 */
    //   overflow: hidden;
    //   /* 超出部分隐藏 */
    //   text-overflow: ellipsis;
    //   /* 显示省略号 */

    // }
    .goodsTop {
        // position: absolute;
        // top: 2%;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .goods_T {
          font-size: 28rpx;
          text-align: left;
          color: #111111;
          max-width: 80%;
          line-height: 28rpx;
          // margin-top: 9px;  //display：flex   中 元素居中
          white-space: nowrap;
          /* 防止文本换行 */
          overflow: hidden;
          /* 超出部分隐藏 */
          text-overflow: ellipsis;
          /* 显示省略号 */

        }

        // 商品价格
        .goods_price {
          font-size: 28rpx;
          color: #111111;
          line-height:28rpx;
        }
      }
    .goods_specs {
      max-width: 80%;
      font-size: 22rpx;
      text-align: left;
      color: #666666;
      min-height: 50rpx;
      display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: normal;
    }

    .goodsBottom {
      // position: absolute;
      // bottom: 10px;
      display: flex;
      align-items: center;
      // justify-content: space-between;
      width: 100%;
      // margin-top: 30px;

      .money {
        font-size: 24rpx;
        text-align: left;
        color: #737373;
        line-height: 24rpx;
      }

      .jifen_box {
        display: flex;
        align-items: center;
        font-size: 24rpx;
        text-align: left;
        // color: #111111;
        color: #737373;
        line-height: 24rpx;
        height: 24rpx;
        margin-left: 6px;
      }
    }
  }
}

.wraper_right {
  font-size: 22rpx;
  color: #666666;
  width: 10%;
  text-align: right;
}

//防止父元素高度塌陷
.clearfix::before
.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

.line_two{
  height: 5px;
  width: 100%;
  background: #f9f9f9;
  line-height: 5px;
}

// 价格明细
.price_detail {
  // padding: 24px;
  background-color: #ffffff;
  margin-top: 10px;
  padding: 24px 24px 75px 24px;

  .price_detail_content {
    border-bottom: 1px solid #f9f9f9;
    padding-bottom: 20px;
  }

  .price_detail_title {
    font-size: 40rpx;
    text-align: left;
    color: #111111;
  }

  .price_detail_box {
    margin-top: 17px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .num {
    font-size: 28rpx;
    text-align: right;
    color: #111111;
  }

  .num_o {
    font-size: 28rpx;
    text-align: right;
    color: #FF6203;
  }

  // 支付方式
  .payment {
    padding: 20px 0px;
    margin-bottom: 40px;
    // display: flex;
    // justify-content: space-between;

    // padding-bottom: 100px;
  }
    .payment_top {
      display: flex;
      justify-content: space-between;
      align-items: center;
  
      .payment_left,.payment_right {
        font-weight: bolder;
      }
      .payment_right {
        display: flex;
        align-items: center;
      }
    }
}

// 需要支付的积分+金额
.payment_num {
  font-weight: bolder;
  display: flex;
  align-items: center;
  font-size: 32rpx;
  color: #111111;
}
// 很多地方字体 颜色公用
.price_detail_name{
  font-size: 28rpx;
  text-align: left;
  color: #111111;
}
// 运费部分
.price_detail_text{
  font-size: 28rpx;
  text-align: right;
  color: #111111;
}
.price_detail_tips{
  font-size: 24rpx;
  text-align: left;
  color: #666666;
  margin-top: 10rpx;
}

.checked-img {
    height: 16px;
    width: 16px;
}

::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep .van-icon {
    color: #242629 !important;
}


::v-deep .van-nav-bar__title {
    font-size: 28rpx;
    color: #333333;
}


::v-deep .van-button--warning{
  background-color: #FF6203;
}

::v-deep .van-icon-success{
  color: #ffffff !important;
}

::v-deep .van-submit-bar__bar{
  display: flex;
  justify-content: space-between !important;
  border-top: 1px solid #f9f9f9;
  height: 72px !important;
  line-height: 72px !important;
}

::v-deep .disabledSubmit .van-button--danger, .van-button--disabled, .van-button--unclickable{
  background-color: #D4D4D4 !important;
  border: 1px solid #D4D4D4 !important;
}

// 向右的箭头
.van-icon-arrow{
  color: #666666 !important;
}
</style>
